﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Shell;
using AxlfVSX.Core;
using EnvDTE;
using Aoxuelf.MDSTool.UI;
using Aoxuelf.MDSTool.Model;
using System.Windows.Forms;

namespace Aoxuelf.MDSTool.Commands
{
    [CommandID(GuidList.guidMDSToolCmdSetString, PkgCmdIDList.cmdidConvertToBLLFunc)]
    public class ConvertToBLLCommand : DynamicCommand
    {
        public ConvertToBLLCommand(Package package)
            : base(package)
        {
        }

        protected override bool CanExecute(OleMenuCommand command)
        {
            try
            {
                if (FileCodeModelHelper.IsDataAccessClass(Dte))
                {
                    CodeFunction func = FileCodeModelHelper.GetCodeFunction(Dte);
                    if (func != null)
                    {
                        string funcName = func.Name;

                        if (funcName.StartsWith("Query") || funcName.StartsWith("Get"))
                        {
                            command.Text = "生成服务层方法（查询）";
                        }
                        else
                        {
                            command.Text = "生成服务层方法（保存）";
                        }

                        return true;
                    }
                }
            }
            catch
            {
                return false;
            }

            return false;
        }

        protected override void OnExecute(OleMenuCommand command)
        {
            try
            {
                CodeFunction func = FileCodeModelHelper.GetCodeFunction(Dte);
                if (func != null)
                {
                    ConvertToBLLMethodInfo methodInfo = new ConvertToBLLMethodInfo();
                    methodInfo.MethodName = func.Name;
                    methodInfo.DALClass = ((CodeClass)func.Parent).Name;
                    methodInfo.DocComment = func.DocComment;
                    methodInfo.IsSave = !(func.Name.StartsWith("Query") || func.Name.StartsWith("Get"));

                    string ss = methodInfo.GenerateMethodString();
                    Clipboard.SetText(ss, TextDataFormat.UnicodeText);
                    MessageBox.Show("已复制到剪贴板！");

                    MDSOutPaneWindow.MDSTool.Clear();
                    MDSOutPaneWindow.MDSTool.WriteLine(ss);
                    MDSOutPaneWindow.MDSTool.Activate();                    
                }                
            }
            catch(Exception ex)
            {
                MDSOutPaneWindow.MDSTool.WriteLine(ex.Message);
                MDSOutPaneWindow.MDSTool.Activate();
            }
        }
    }
}
